package code5;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerReceiveFile extends Thread {

    private String str = null;

    public ServerReceiveFile(String str){this.str=str;}

    @Override
    public void run(){

        Socket s = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        ServerSocket ss = null;

        try {
            ss = new ServerSocket(1234);
            s = ss.accept();
            InetAddress inetAddress = s.getInetAddress();
            System.out.println("服务器准备接收客户端"+inetAddress+"发送的文件！");

            // 对客户端发送的信息进行解析，得到文件名称
            String[] s1 = str.split(" ");
            String[] s2 = s1[1].split("/");
            String fileName = s2[s2.length-1];

            dis = new DataInputStream(s.getInputStream());

            // 要准备服务器接收文件的文件夹
            File file = new File("F:/ServerReceivedFile/"+fileName);
            dos = new DataOutputStream(new FileOutputStream(file));

            byte[] barr = new byte[1024];
            int res = 0;
            while((res=dis.read(barr))!=-1){
                dos.write(barr,0,res);
                dos.flush();
            }
            System.out.println("文件"+fileName+"接收完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null!=dos){
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=dis){
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null!=ss){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
